using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using WeatherSystem.API.Data;

namespace WeatherSystem.Tests;

// 自定义测试工厂：
// - 使用 InMemory 数据库，避免改动真实数据库文件
// - 关闭后台HostedService，避免测试期间产生噪音
public class WebAppFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            // 替换 DbContext 为 InMemory
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(DbContextOptions<WeatherDbContext>));
            if (descriptor is not null)
            {
                services.Remove(descriptor);
            }

            services.AddDbContext<WeatherDbContext>(options =>
            {
                options.UseInMemoryDatabase("WeatherSystem_TestDb");
            });

            // 移除并禁用后台采集HostedService（如果有）
            var hosted = services.Where(d => d.ServiceType.Name.Contains("HostedService")).ToList();
            foreach (var h in hosted)
            {
                services.Remove(h);
            }
        });
    }
}